package com.cdream.basic.algorithm.leetcode.slideWindow;

import java.util.HashMap;
import java.util.Map;

/**
 * @author cdream
 * @date 6/3/21
 */
public class Question525 {
    public static void main(String[] args) {
        System.out.println(new Question525().findMaxLength(new int[]{0, 1, 1}));
    }

    public int findMaxLength(int[] nums) {
        Map<Integer, Integer> mp = new HashMap<>();
        mp.put(0, -1);
        int sum = 0;
        int maxLength = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 1) {
                sum++;
            } else {
                sum--;
            }
            Integer lastIndex = mp.get(sum);
            if (lastIndex == null) {
                mp.put(sum, i);
            } else {
                maxLength = Math.max(i - lastIndex, maxLength);
            }

        }
        return maxLength;

    }
}
